package com.boarsoft.boar.log;

import javax.websocket.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.context.ActionContext;
import com.boarsoft.boar.deploy.plan.bean.BuildRequest;
import com.boarsoft.cache.Cache;
import com.boarsoft.common.Util;
import com.boarsoft.message.bean.Message;
import com.boarsoft.message.core.MessageService;
import com.boarsoft.web.websocket.WebsocketEndpoint;
import com.boarsoft.web.websocket.WebsocketMessage;

/**
 * 
 * @author Mac_J
 *
 */
@Component("deployLogSvc")
public class DeployLogSvc implements MessageService {
	private static final Logger log = LoggerFactory.getLogger(DeployLogSvc.class);

	@Override
	public void put(Message m) throws Exception {
		log.info("Received deploy log ==> {}", m.getContent());
		String key = m.getKey();
		if (Util.strIsEmpty(key)) {
			log.warn("Drop deploy log without key ==> {}", m.getContent());
			return;
		}
		Cache cache = ActionContext.getCache();
		BuildRequest po = (BuildRequest) cache.get("deploy", key);
		// String[] a = key.split("/");
		// String sessionId = a[0];
		// String taskId = a[1];
		// // String env = a[2];
		String wssid = po.getWssid();
		Session session = WebsocketEndpoint.getSession(wssid);
		if (session == null) {
			log.warn("Drop deploy log with invalid key {} ==> {}", wssid, m.getContent());
			return;
		}
		WebsocketMessage mw = new WebsocketMessage();
		mw.setGroup("deploy");
		mw.setCode("log");
		mw.setToken(po.getId());
		mw.setData(m.getContent());
		WebsocketEndpoint.send(mw, wssid);
	}
}